package application;

import domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.inject.Singleton;
import java.io.Serializable;
import java.util.Date;

/**
 * Personal logger.
 * <p/>
 * Analýza požadavků verze 3 (finální)
 * 1.2.3 Logování akcí
 * Systém bude automaticky ukládat záznamy o provedených akcích. Bude se logovat přihlášení
 * uživatele, odeslání objednávky, změna nastavení správcem a požadavek na změnu hesla
 * uživatelem. U každého logu bude uveden čas, jméno uživatele a o kterou z akcí šlo.
 */
@Singleton
public class MyLogger {

    private static final Log logger = LogFactory.getLog(MyLogger.class);

    public static enum ActionType {

        USER_LOGGED, ORDER_SENDED, CHANGE_SETTINGS, PASSWORD_CHANGE_REQUEST
    }

    public MyLogger() {
    }

    /**
     * Save log.
     *
     * @param time       java.util.Date time. - you should send full Date object.
     * @param userLogin  login of user who trigger event.
     * @param actionType USER_LOGGED, ORDER_SENDED, CHANGE_SETTINGS or PASSWORD_CHANGE_REQUEST.
     */
    public void log(Date time, String userLogin, ActionType actionType) {
        logger.info(new WrappedLog(time, userLogin, actionType));
    }

    /**
     * Save log.
     *
     * @param time       java.util.Date time.
     * @param user       user who trigger event.
     * @param actionType USER_LOGGED, ORDER_SENDED, CHANGE_SETTINGS or PASSWORD_CHANGE_REQUEST.
     */
    public void log(Date time, User user, ActionType actionType) {
        log(time, user.getLogin(), actionType);
    }

    /**
     * WrappedLog class for one log record.
     */
    private final class WrappedLog implements Serializable {

        private static final long serialVersionUID = 1L;
        private Date time;
        private String userLogin;
        private ActionType actionType;

        public WrappedLog(Date time, String userLogin, ActionType actionType) {
            this.time = time;
            this.userLogin = userLogin;
            this.actionType = actionType;
        }

        public ActionType getActionType() {
            return actionType;
        }

        public Date getTime() {
            return time;
        }

        public String getUserLogin() {
            return userLogin;
        }

        @Override
        public String toString() {
            return "Action: " + actionType + ", time: " + time.toString() + ", login: " + userLogin;
        }
    }
}
